const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080, host: '0.0.0.0' });

// 存储客户端ID到连接的映射
const clients = new Map();

wss.on('connection', (ws) => {
  console.log('客户端已连接');

  ws.on('message', (data) => {
    const message = JSON.parse(data.toString());
    // 处理注册消息
    if (message.type === 'register') {
      clients.set(message.id, ws);
      ws.send(JSON.stringify({ type: 'register-success' }));
      console.log(`客户端ID ${message.id} 注册成功`);
      return;
    }
    // 转发消息到目标客户端
    if (message.to) {
      const targetClient = clients.get(message.to);
      if (targetClient && targetClient.readyState === WebSocket.OPEN) {
        targetClient.send(JSON.stringify(message));
        console.log('message',JSON.stringify(message));
        
        console.log(`转发${message.type}消息从${message.from}到${message.to}`);
      } else {
        ws.send(JSON.stringify({ type: 'error', error: '目标客户端未找到' }));
      }
    }
  });

  ws.on('close', () => {
    // 从映射中移除断开的客户端
    for (const [id, client] of clients) {
      if (client === ws) {
        clients.delete(id);
        console.log(`客户端ID ${id} 已断开`);
        break;
      }
    }
  });
});

console.log('信令服务器运行在 ws://localhost:8080');